package senders;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import sr.logger.Logger;

import client.remote.ClientReceiver;


public class ChatBroadCaster extends Thread
{
	Logger logger = Logger.getLogger(this.getClass());
	private IBroadcaster masterBroadCaster;
	private BlockingQueue<String> messageQueue = new LinkedBlockingQueue();
	private boolean shutdown = false;
	private boolean inMainRoom;
	public ChatBroadCaster(IBroadcaster bc,boolean inMainRoom)
	{
		this.inMainRoom = inMainRoom;
		masterBroadCaster = bc;
		start();
	}
	public void addMessage(String msg)
	{
		try {
			messageQueue.put(msg);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void shutdown()
	{
		shutdown = true;
	}
	@Override
	public void run()
	{
		
		while(!shutdown)
		{
			String  msg = null;
			try {
				msg = messageQueue.poll(1, TimeUnit.SECONDS);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(msg != null)
			{
				logger.log("run","broadcasting main chat msg");
				ArrayList<ClientReceiver> clients = new ArrayList<ClientReceiver>(masterBroadCaster.getClients());
				System.out.println("Broadcasting to " + clients.size());
				Long tick = logger.log("run","addMessage/addRoomMessage");
				for(ClientReceiver client : clients)
				{
					try 
					{
						
						if(inMainRoom)
							client.addMessage(msg,tick);
						else
							client.addRoomMessage(msg,tick);
					} 
					catch (RemoteException e) 
					{
						masterBroadCaster.reportError(client);
						e.printStackTrace();
					}
				}
			}
		}
	}
}
